package view.diaLogView;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.text.Framgnet.HomeFragment;
import com.example.administrator.text.R;
import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import app.MyApplication;
import data.SharedPreferencesUtils;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;

/**
 * Created by liuxiaobin on 2017/4/17
 * 优惠券的 弹出框
 */

public class CouponDialog extends Dialog{
    private Context mContext;
    private JSONArray mJsonArray;
    private CouponDialog mCouponDialog;
    private TextView mTv1,mTv2,mTv3;
    private int mTicketid,mTiveTime; //mTiveTime送的时长
    private int mPosition = 0;//mPosition对应数组的下标
    private boolean mTv3Clickable = true;
    private Logger mLogger = Logger.getLogger(HomeFragment.class);

    @Override
    public void show() {
        Window window = getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.share_style);
        super.show();
    }

    protected CouponDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public CouponDialog(Context context, JSONArray jsonArray) {
        super(context, R.style.upoad_dialog);
        this.mContext = context;
        this.mJsonArray = jsonArray;
        mCouponDialog = this;
        mPosition = 0;

    }

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.width = mContext.getResources().getDisplayMetrics().widthPixels;
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View mView = inflater.inflate(R.layout.dialog_coupon, null);
        LinearLayout linearLayoutTop = (LinearLayout)mView.findViewById(R.id.dialog_coupon_top);
        LinearLayout linearLayoutButton = (LinearLayout)mView.findViewById(R.id.dialog_coupon_button);
        mTv1 = (TextView)mView.findViewById(R.id.dialog_coupon_tv1);
        mTv2 = (TextView)mView.findViewById(R.id.dialog_coupon_tv2);
        mTv3 = (TextView)mView.findViewById(R.id.dialog_coupon_tv3);
        try {
            JSONObject jsonObject = mJsonArray.getJSONObject(mPosition);
            String ticketName = jsonObject.getString("ticketName");
            String explain = jsonObject.getString("explain");
            mTicketid  = jsonObject.getInt("ticketid");
            mTiveTime = mTiveTime +jsonObject.getInt("giveTime");
            mTv1.setText(ticketName);
            mTv2.setText(explain);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mTv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mTv3Clickable && mTv3.getText().toString().equals("笑纳")){
                    mTv3.setText("领取中");
                    LogUtil.eE("",".......mTv3............的点击事件");
                    mTv3Clickable = false;
                    tv3OnClick();
                }
            }
        });
        setContentView(mView,params);
    }

    /**
     * 领取券
     */
    private void tv3OnClick(){
        HashMap map = new HashMap<>();
        String id = (String) SharedPreferencesUtils.getParam(mContext, HomeUtil.mUseridDB,"");
        String token = (String) SharedPreferencesUtils.getParam(mContext, HomeUtil.mTokenDB,"");
        map.put("userid",id);
        map.put("ticketid",mTicketid);
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.getUrlNew().RECEIVE_COUPON,stringJson,token,id,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,token,id,Url.getUrlNew().RECEIVE_COUPON,stirngSign,time);
        mLogger.info("getCoupon()--fwq"+ MyApplication.getApp().getFWQString()+"stringJson"+stringJson+"..mPosition.."+mPosition);
        GreenTreeNetworkUtil.getInstance().doPost(mContext,MyApplication.getApp().getFWQString(),1,map1,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    mLogger.info("getCoupon()--onSuccess().."+response);
                    mTv3Clickable = true;
                    int code = jsonObject.getInt("code");
                    if(code == 1){
                        okReceive();
                    }else if(code == -1){
                        mTv3.setText("笑纳");
                        Toast.makeText(mContext,mContext.getString(R.string.FWQ), Toast.LENGTH_SHORT).show();
                    }else if(code == -2){
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(mContext);
                        crowdRetunDialog.show();
                        mCouponDialog.dismiss();
                    }else {
                        Toast.makeText(mContext,"领取失败",Toast.LENGTH_SHORT).show();
                        mTv3.setText("笑纳");
                    }

                } catch (JSONException e) {
                    mTv3Clickable = true;
                    e.printStackTrace();
                    Toast.makeText(mContext,"领取失败",Toast.LENGTH_SHORT).show();
                    mTv3.setText("笑纳");
                }

            }

            @Override public void onFailure(Throwable error) {
                mTv3Clickable = true;
                mTv3.setText("笑纳");
                Toast.makeText(mContext,"领取失败",Toast.LENGTH_SHORT).show();
                mLogger.info("getCoupon()--onFailure().."+error);
            }
        });
    }

    /**
     * 领取成功的操作
     */
    private void okReceive(){

        mPosition++;
        if(mPosition >= mJsonArray.length()){
            mTv3.setText("领取成功");
            int time = (int) SharedPreferencesUtils.getParam(mContext,HomeUtil.mVIPTime,3);
            SharedPreferencesUtils.setParam(mContext, HomeUtil.mVIPTime,mTiveTime*60+time);
            HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mCouponDialog.dismiss();
                }
            },500);

            if(mTiveTime>0){
                HashMap<String,Object> hashMap = new HashMap<>();
                hashMap.put("code","WiFi");
                hashMap.put("target","vip");
                hashMap.put("time",mTiveTime);
                String stringJson = StringUtil.getStringUtilNew().hashMapToJson(hashMap); //参数包
                EventBus.getDefault().post(stringJson);
                EventBus.getDefault().post("balance");
            }
        }else {
            try {
                mTv3.setText("笑纳");
                Toast.makeText(mContext,"领取成功",Toast.LENGTH_SHORT).show();
                JSONObject jsonObject = mJsonArray.getJSONObject(mPosition);
                String ticketName = jsonObject.getString("ticketName");
                String explain = jsonObject.getString("explain");
                mTicketid  = jsonObject.getInt("ticketid");
                mTiveTime = mTiveTime +jsonObject.getInt("giveTime");
                mTv1.setText(ticketName);
                mTv2.setText(explain);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
